﻿using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Drawing.Imaging;
using System.IO;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.ViewFeatures;
using Microsoft.AspNetCore.SignalR;
using MongoDB.Bson;
using MongoDB.Driver;
using NetCoreQrCoreDemo.Common;
using NetCoreQrCoreDemo.Models;
using NetCoreQrCoreDemo.Tools;

namespace NetCoreQrCoreDemo.Controllers
{
    public class HomeController : Controller
    {
        private readonly IHostingEnvironment _hostingEnvironment;
        //注入
        private IQrCode qrCode;
       public HomeController(IQrCode _qrCode,IHostingEnvironment hostingEnvironment)
       {
           qrCode = _qrCode;
           _hostingEnvironment = hostingEnvironment;
       }
        public IActionResult Index()
        {
            return View();
        }

        public IActionResult Privacy()
        {
            return View();
        }

        [ResponseCache(Duration = 0, Location = ResponseCacheLocation.None, NoStore = true)]
        public IActionResult Error()
        {
            return View(new ErrorViewModel { RequestId = Activity.Current?.Id ?? HttpContext.TraceIdentifier });
        }

        //手动更换
        public IActionResult NewMessage(string cid)
        {
           //await InfoHub.GlobalHub.Clients.Client("cid").SendAsync("GetClientId", new { Cid = cid, NewCode = Guid.NewGuid() });
           Startup.GlobalHub.InvokeByIDAsync(cid, "GetClientId", new {Cid = cid, NewCode = Guid.NewGuid()});
            return Json(111);
        }
        //简单的富文本编辑器
        public IActionResult Editer(string id)
        {
            if (!string.IsNullOrEmpty(id))
            {
                var nid = ObjectId.Parse(id);
                var helper = new MongoHelper(ConstFields.MongodbStr, ConstFields.MongodbDbName);
                var model = helper.FindNoe<MyArticle>(x => x._id == nid);
                if (model == null) model = new MyArticle();
                return View(model);
            }
            return View(new MyArticle());
        }

        [HttpPost]
        public async Task<IActionResult> SaveImage()
        {
            var files = Request.Form.Files;
            long size = files.Sum(f => f.Length);
            
            string webRootPath = _hostingEnvironment.WebRootPath;
            string contentRootPath = _hostingEnvironment.ContentRootPath;
            string filesnames="";
            foreach (var formFile in files)
            {
                if (formFile.Length > 0)
                {

                    string fileExt = GetFileExt(formFile.FileName); //文件扩展名，不含“.”
                    long fileSize = formFile.Length; //获得文件大小，以字节为单位
                    string newFileName = System.Guid.NewGuid().ToString() + "." + fileExt; //随机生成新的文件名
                    var filePath = webRootPath + "/upload/" + newFileName;
                    filesnames= "/upload/" + newFileName;
                    using (var stream = new FileStream(filePath, FileMode.Create))
                    {
                        await formFile.CopyToAsync(stream);
                    }
                }
            }
            return Json(new { uploaded=1, url=filesnames });
        }

        [HttpPost]
        public async Task<IActionResult> SaveHtml([FromForm] MyArticle article)
        {
            var helper = new MongoHelper(ConstFields.MongodbStr,ConstFields.MongodbDbName);
            if (article.status)
            {
                await helper.InsertAsync<MyArticle>(article);
            }
            else
            {
                //注意 ObjectId 传回的时候 这个类型不会自动赋值  需要重新赋值
                var ids = Request.Form["_id"];
                article._id = ObjectId.Parse(ids);
                article.updatetime = $"{DateTime.Now:yyyy-MM-dd HH:mm:ss}";
                var fiter = Builders<MyArticle>.Filter.Eq("_id", article._id);
                var update = Builders<MyArticle>.Update.Set("title", article.title)
                    .Set("content", article.content).Set("updatetime",article.updatetime);
                 helper.UpdateMany(fiter, update);
            }
           
           return Json(new {msg = "保存成功", data = article});
        }
         
        public IActionResult LoadArticle(string id)
        {
            if (!string.IsNullOrEmpty(id))
            {
                var nid = ObjectId.Parse(id);
                var helper = new MongoHelper(ConstFields.MongodbStr, ConstFields.MongodbDbName);
                var model=helper.FindNoe<MyArticle>(x => x._id == nid);
                if(model==null) model=new MyArticle();
                return View(model);
            }

            return View(new MyArticle());
        }

        public IActionResult ArticleList()
        {
            var helper = new MongoHelper(ConstFields.MongodbStr, ConstFields.MongodbDbName);
            var list = helper.GetList<MyArticle>();
            return View(list);
        }
        //浏览图片
        public IActionResult ViewImages()
        {
            return View();
        }
        private string GetFileExt(string formFileFileName)
        {
            return formFileFileName.Contains(".") ? formFileFileName.Split('.').Last() : "jpg";
        }

        //二维码图片
        public void QrCodeImg()
        {
            Response.ContentType = "image/jpeg";
            var bitmap = qrCode.GetQrCode("https://blog.csdn.net/u014038245/article/details/83419020", 5);
            MemoryStream ms = new MemoryStream();
            bitmap.Save(ms, ImageFormat.Jpeg);
            Response.Body.WriteAsync(ms.GetBuffer(), 0, Convert.ToInt32(ms.Length));
            Response.Body.Close();
        }
    }
}
